#!/usr/bin/env python3
#
# Generate a bootstrap.sh script by pulling out commands from DEPS.txt files.
#
# Usage:
#
#     $ python ./tools/bootstrap.py
#
import os
import sys


def GetPlatformNameOrDie():
    """Return the platform name, one of: {linux,macos}."""
    if sys.platform == "linux" or sys.platform == "linux2":
        return "linux"
    elif sys.platform == "darwin":
        return "macos"
    else:
        print("Unsupported platform: {}".format(sys.platform), file=sys.stderr)
        sys.exit(1)


def EmitDependencyCommandsFromPathOrDie(path, visited_set, platform, file):
    """Read the dependency file and write out the commadns to execute."""

    def Emit(line, linenum):
        print(line, " # from:", path + ":" + str(linenum), file=file)

    with open(path) as f:
        for i, line in enumerate(f.read().rstrip().split("\n")):
            if line.startswith("#"):
                Emit(line, i + 1)
            elif line.startswith("all: "):
                cmd = line[len("all: ") :]
                if cmd not in visited_set:
                    visited_set.add(cmd)
                    Emit(cmd, i + 1)
            elif line.startswith("{}: ".format(platform)):
                cmd = line[len(platform) + 2 :]
                if cmd not in visited_set:
                    visited_set.add(cmd)
                    Emit(cmd, i + 1)


def CreateBootstrapScriptOrDie(platform):
    """Create a ./bootstrap.sh script with additional dependencies to install."""
    with open("bootstrap.sh", "w") as f:
        print(f"# Script generated by {sys.argv[0]}.", file=f)
        print("set -eux", file=f)
        visited_set = set()

        for root, _, file_names in os.walk("."):
            if "DEPS.txt" in file_names:
                path = os.path.join(root, "DEPS.txt")
                EmitDependencyCommandsFromPathOrDie(path, visited_set, platform, f)

    print("Created bootstrap script to install system dependencies.")
    print("Inspect and then run the script:")
    print("    bash ./bootstrap.sh")


if __name__ == "__main__":
    CreateBootstrapScriptOrDie(GetPlatformNameOrDie())
